/*
 * DataReader.cpp
 *
 *  Created on: Oct 1, 2010
 *      Author: blyth
 */

#include <SimDataReader.h>
#include <TBranch.h>
#include <cstring>
#include <iostream>
#include <globals.hh>

SimDataReader::SimDataReader(char* path, int maxPhotons) :
	maxPhotons(maxPhotons) {
	file = new TFile(path);
	index = -1;
	photon = 0;
	tree = NULL;
	cout << endl;
}

SimDataReader::~SimDataReader() {
	file->Close();
}

bool SimDataReader::ReadNext(double& OEVEnergy, double& energy, int& hitCount) {
	if (photon == 0) {
		index++;
		cout << "\r" << index << flush;
		ss.str("");
		ss << "eventNumber" << index;
		tree = (TTree*) file->Get((ss.str()).c_str());
		if (!tree)
			return false;
	}

	ss.str("");
	ss << "photonNumber" << photon;
	dataBranch = tree->GetBranch(ss.str().c_str());
//	if (dataBranch->GetEntryNumber() == 0) {
//		energy = 0;
//		OEVEnergy = 0;
//		photon = maxPhotons;
//		cleanup();
//		return this->ReadNext(OEVEnergy, energy);
//	}
	dataBranch->SetAddress(&data);
	for (int i = 0; i < dataBranch->GetEntryNumber(); i++) {
		dataBranch->GetEvent(i);
		energy += data.energy / MeV;
	}
	if (dataBranch->GetEntryNumber() > 0) {
			hitCount++;
	}
	ss << "OEV";
	OEVBranch = tree->GetBranch(ss.str().c_str());
	OEVBranch->SetAddress(&data);
	for (int i = 0; i < OEVBranch->GetEntryNumber(); i++) {
		OEVBranch->GetEvent(i);
		OEVEnergy += data.energy / MeV;
	}

	cleanup();

	if (photon > 0)
		return this->ReadNext(OEVEnergy, energy, hitCount);
	return true;
}

void SimDataReader::cleanup() {
	photon++;
	if (photon >= maxPhotons) {
		photon = 0;
		tree->Delete();
	}
}
